package com.sun.local.top;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.sun.common.constants.Constant.SSQ_FILE_PATH;

/**
 * 各类数据排行榜
 */
public class TopData {

    public static void main(String[] args) throws Exception {
        getTopAll();
    }

    public static void getTopAll() throws IOException {
        // 读取文件数据
        List<String> lines = Files.readAllLines(Paths.get(SSQ_FILE_PATH));

        // 获取Top数据
        getTop(lines,"AC", 2);
        getTop(lines,"SerialNumber", 2);
        getTop(lines,"SUM", 10);
        getTop(lines,"OddEvenRatio", 3);
        getTop(lines,"Distribution", 3);

        System.out.println("*******************************************");

        // 获取所有Top数据
        getAllTop(lines,"AC", 10);
        getAllTop(lines,"SerialNumber", 10);
        getAllTop(lines,"SUM", 200);
        getAllTop(lines,"OddEvenRatio", 10);
        getAllTop(lines,"Distribution", 30);
    }

    /**
     * 获取Top数据并写出到文件ssq_top.text
     * @param lines 文件数据
     * @param type 类型
     * @param top 排名
     */
    private static void getTop(List<String> lines, String type, int top) {
        // 统计AC值出现次数
        Map<String, Long> acCounts = lines.stream()
                .filter(line -> line.contains(type + "="))
                .map(line -> StringUtils.substringBetween(line, type + "=", "|").trim())
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        // 获取排名前N的数据并写出
        acCounts.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .limit(top)
                .forEach(e -> {
                    System.out.println(type + "=" + e.getKey() + ",Count=" + e.getValue());
                });
    }

    /**
     * 获取Top数据并写出到文件ssq_top.text
     * @param lines 文件数据
     * @param type 类型
     * @param top 排名
     */
    private static void getAllTop(List<String> lines, String type, int top) {
        // 统计AC值出现次数
        Map<String, Long> acCounts = lines.stream()
                .filter(line -> line.contains(type + "="))
                .map(line -> StringUtils.substringBetween(line, type + "=", "|").trim())
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        // 获取排名前N的数据并写出
        acCounts.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .limit(top)
                .forEach(e -> {
                    System.out.println(type + "=" + e.getKey() + ",Count=" + e.getValue());
                });
    }

}
